import cv2
import os
import dlib
from skimage import io
import csv
import numpy as np

# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# Dlib 人脸预测器
predictor = dlib.shape_predictor("/Users/yangyafei/Desktop/face/dlibfile/shape_predictor_68_face_landmarks.dat")
# Dlib 人脸识别模型，将人脸映射成128D矢量
face_rec = dlib.face_recognition_model_v1("/Users/yangyafei/Desktop/face/dlibfile/dlib_face_recognition_resnet_model_v1.dat")


# 返回单张图像的 128D 特征
def return_128d_features(path_img):
    img_rd = io.imread(path_img)
    img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)
    faces = detector(img_gray, 1)
    print("%-40s %-20s" % ("正在处理的人脸图像 / image with faces detected:", path_img), '\n')
    # 确保检测到是人脸图像去算特征
    if len(faces) != 0:
        shape = predictor(img_gray, faces[0])
        face_descriptor = face_rec.compute_face_descriptor(img_gray, shape)
    else:
        face_descriptor = 0
        print("no face")
    return face_descriptor


def reFlushFaceDB():
    # 要读取人脸图像文件的路径
    path_images_from_our = "C:/Users/86136/Desktop/faces/"
    # 读取每个人人脸图像的数据
    people = os.listdir(path_images_from_our)
    os.listdir()
    print(people)
    with open("/Users/yangyafei/Desktop/features_all.csv", "w", newline="") as csvfile:
        writer = csv.writer(csvfile)
        for person in people:
            # for i in range(0,2):
            print("******" + person + "****** Processing")
            features_128d = return_128d_features(path_images_from_our + "/" + person)
            print("特征值 / The features:", list(features_128d))
            writer.writerow(features_128d)  # 按行写入到Csv文件中
            print('\n')
        print(
            "人脸数据存入 / Save all the features of faces registered into: C:/Users/86136/Desktop/features_all.csv")

#reFlushFaceDB()